<template>
  <div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="top" label-width="80px"
             class="demo-ruleForm" size="large">

      <el-form-item label="UserId">
        <el-input v-model="ruleForm.id" readonly style="width:300px"></el-input>
      </el-form-item>
      <el-form-item label="Password" prop="password">
        <el-input v-model="ruleForm.password" style="width:300px"></el-input>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>


<script>
import JSEncrypt from 'jsencrypt/bin/jsencrypt';

export default {
  data() {
    return {

      //表格数据
      ruleForm: {
        id: this.$route.query.id,
        password: this.$route.query.password
      },
      rules: {
        password: [
          {required: true, message: '请输入正确的内容', trigger: 'blur'},
        ]
      },
    };
  },
  methods: {

    submitForm(formName) {

      const _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //这个是更新数据库的操作，data为请求参数
          //首先发送请求，获得服务器的公钥，用于前端加密
          axios({
            method: 'GET',
            url: ' http://115.29.176.82:8081/manager/api/account/key'
          }).then(function (resp) {
            //拿到公钥后进行正式的更新
            axios({
              method: 'PATCH',
              url: 'http://115.29.176.82:8081/manager/api/account',
              data: {
                id: _this.ruleForm.id,
                //把密码通过拿到的公钥进行加密
                password: _this.encrypt(_this.ruleForm.password, resp.data.data.key)
              }
            }).then(function (resp) {
              if (resp.data.status === 200) {
                alert('修改成功');
              }
              else {
                alert(resp.data.error);
              }
            });
          });
        }
        else {
          alert('ERROR！请修改您的数据后再次提交');
          return false;
        }
      });

    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //解密的方法
    decrypt(data, privateKey) {
      let encryptor = new JSEncrypt();
      encryptor.setPrivateKey(privateKey);
      return encryptor.decrypt(data);
    },


    encrypt(data, publicKey) {
      let encryptor = new JSEncrypt();
      encryptor.setPublicKey(publicKey);
      return encryptor.encrypt(data);
    }
  },
};
</script>